package com.angel.webapp.actions.impl;

import com.angel.architecture.exceptions.NonBusinessException;
import com.angel.common.keyValue.KeyValueResult;
import com.angel.email.application.ApplicationEmailConnections;
import com.angel.email.connection.IncomingEmailConnection;
import com.angel.webapp.actions.ActionStrategy;
import com.angel.webapp.file.FileInformation;

/**
 * @author William
 * @since 13/August/2009
 */
public class EmailAttachmentActionStrategy implements ActionStrategy {

	private static final String EMAIL_MESSAGE_ID = "emailMessageID";
	private static final String EMAIL_CONNECTION_NAME = "emailConnectionName";
	private static final String EMAIL_MESSAGE_FOLDER_NAME = "emailMessageFolderName";

	public FileInformation doAction(KeyValueResult keyValueResult) {
		String emailMessageID = keyValueResult.getResultFor(EMAIL_MESSAGE_ID).toString();
		String emailConnectionName = keyValueResult.getResultFor(EMAIL_CONNECTION_NAME).toString();
		String emailFolderName = keyValueResult.getResultFor(EMAIL_MESSAGE_FOLDER_NAME).toString();
		IncomingEmailConnection emailConnection = (IncomingEmailConnection) ApplicationEmailConnections.createInstance().findEmailConnection(emailConnectionName);
		FileInformation fileInformation;
		try {
			Integer messageNumber = Integer.valueOf(emailMessageID);
			fileInformation = emailConnection.getAttachmentForMessage(emailFolderName, messageNumber);
		} catch (NumberFormatException e) {
			throw new NonBusinessException("It is not valid number format for message number [" + emailMessageID + "].", e);
		}
		return fileInformation;
	}
}